package com.lanwf.admin.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.Ret;
import com.jfinal.upload.UploadFile;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.List;

/**
 * @Auther: Lanwf
 * @Date: 2021/12/23 17:57
 * @Description:
 */
public class AdminXssInterceptor implements Interceptor {


    private static String files = "img,png,gif,IMG,PNG,FIG";

    @Override
    public void intercept(Invocation inv) {
        HttpServletRequest request = inv.getController().getRequest();
        //非法文件上传
        try {
            List<UploadFile> files = inv.getController().getFiles();
            if(files != null){
                for (UploadFile file : files) {

                }
            }
        } catch (Exception e) {
        }

        //防止xss存储攻击
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String key = headerNames.nextElement();
            String value = request.getParameter(key);
            if(value != null && !value.equals(StringEscapeUtils.escapeHtml4(value))){
                inv.getController().renderJson(Ret.fail("msg","该请求存在渗透风险请检查"));
                return;
            }
        }
        //防止表单非法提交
        if(request.getRequestURI().contains("update") || request.getRequestURI().contains("save")){
            String formKey = request.getParameter("formKey");

            if(StringUtils.isBlank(formKey)){
                inv.getController().renderJson(Ret.fail("msg","非法数据请求"));
                return;
            }
        }

        inv.invoke();
    }

}
